import { View, Picker, Image, Map } from "@tarojs/components";
import {
  AtList,
  AtListItem,
  AtForm,
  AtInput,
  AtButton,
  AtMessage
} from "taro-ui";
import { useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  addPointApi,
  adjustPointApi,
  getPointListApi
} from "../../../utils/api";
import { qtb, btq } from "../../../utils/to";
import { baseUrl } from "../../../utils/http";

import "./index.scss";

import { useSelector, useDispatch } from "react-redux";

const selector = [
  {
    type: 1,
    title: "未启用"
  },
  {
    type: 2,
    title: "启用"
  }
];

const Index = () => {
  const { id, lng, lat } = useRouter().params;

  const satellite = useSelector(state => state.yq.satellite);
  const level = useSelector(state => state.yq.level);
  const lon2 = useSelector(state => state.yq.lon2);
  const lat2 = useSelector(state => state.yq.lat2);
  const dispatch = useDispatch();

  useDidShow(() => {
    getList();
  });

  const [state, setState] = useState({
    name: "",
    tag: "",
    pointstate: {
      type: 1,
      title: "未启用"
    }
  });

  const [markers, setmarkers] = useState([]);
  const [added, setAdded] = useState(false);

  const mapClick = e => {
    if (added) {
      setmarkers(markers => {
        markers.pop();
        return [
          ...markers,
          {
            latitude: +e.detail.latitude,
            longitude: +e.detail.longitude,
            title: "布点名称:",
            iconPath:
              baseUrl +
              "/static/icon_" +
              (state.pointstate.type === 1 ? "red" : "green") +
              ".png",
            width: 40,
            height: 60
          }
        ];
      });
    } else {
      setmarkers(markers => [
        ...markers,
        {
          latitude: +e.detail.latitude,
          longitude: +e.detail.longitude,
          title: "布点名称:",
          iconPath:
            baseUrl +
            "/static/icon_" +
            (state.pointstate.type === 1 ? "red" : "green") +
            ".png",
          width: 40,
          height: 60
        }
      ]);
      setAdded(true);
    }
  };

  const fn = () => {
    setmarkers(markers => {
      markers[markers.length - 1].longitude =
        markers[markers.length - 1].longitude - 0.00001;
      return [...markers];
    });
  };

  const fn2 = () => {
    setmarkers(markers => {
      markers[markers.length - 1].longitude =
        markers[markers.length - 1].longitude + 0.00001;
      return [...markers];
    });
  };

  const fn3 = () => {
    setmarkers(markers => {
      markers[markers.length - 1].latitude =
        markers[markers.length - 1].latitude + 0.00001;
      return [...markers];
    });
  };

  const fn4 = () => {
    setmarkers(markers => {
      markers[markers.length - 1].latitude =
        markers[markers.length - 1].latitude - 0.00001;
      return [...markers];
    });
  };

  const changename = value => {
    setState(state => ({
      ...state,
      name: value
    }));
  };

  const changetag = value => {
    setState(state => ({
      ...state,
      tag: value
    }));
  };

  const changestate = e => {
    setState(state => ({
      ...state,
      pointstate: selector[e.detail.value]
    }));
    if (added) {
      setmarkers(markers => {
        markers[markers.length - 1].iconPath =
          baseUrl +
          "/static/icon_" +
          (e.detail.value === "0" ? "red" : "green") +
          ".png";
        return [...markers];
      });
    }
  };

  // 获取数据
  const getList = async keyword => {
    const res = await getPointListApi({
      project_id: id,
      get_count: 1000,
      start_index: 0,
      point_keyword: keyword || ""
    });
    if (res.res === 0) {
      const mks = res.records.map(item => {
        const arr = btq(item.longitude / 1000000, item.latitude / 1000000);
        if (item.state === 1) {
          return {
            latitude: arr[1],
            longitude: arr[0],
            title: "布点名称:" + item.name,
            iconPath: baseUrl + "/static/icon_red.png",
            width: 40,
            height: 60
          };
        } else {
          return {
            latitude: arr[1],
            longitude: arr[0],
            title: "布点名称:" + item.name,
            iconPath: baseUrl + "/static/icon_green.png",
            width: 40,
            height: 60
          };
        }
      });
      setmarkers(mks);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const onSubmit = async () => {
    const res = await addPointApi({
      project_id: id,
      name: state.name,
      tag: state.tag,
      state: state.pointstate.type
    });
    if (res.res === 0) {
      if (added) {
        dispatch({
          type: "changeMap",
          lon: markers[markers.length - 1].longitude,
          lat: markers[markers.length - 1].latitude
        });
        const arr = qtb(
          markers[markers.length - 1].longitude,
          markers[markers.length - 1].latitude
        );
        const res2 = await adjustPointApi({
          point_id: res.id,
          longitude: arr[0],
          latitude: arr[1]
        });
        if (res2.res === 0) {
          Taro.atMessage({
            message: "新增成功",
            type: "success"
          });
          Taro.navigateBack({
            delta: 1
          });
        } else {
          Taro.atMessage({
            message: res.msg,
            type: "warning"
          });
        }
      } else {
        Taro.atMessage({
          message: "新增成功, 但未设置经纬度",
          type: "success"
        });
        Taro.navigateBack({
          delta: 1
        });
      }
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const changeSatellite = () => {
    dispatch({ type: "changeSatellite" });
  };

  const regionChange = e => {
    if (e.detail.scale) {
      dispatch({ type: "changeScale", scale: e.detail.scale });
    }
  };

  return (
    <View className="lonlat">
      <View className="mapwrap">
        <Map
          longitude={lon2 || lng}
          latitude={lat2 || lat}
          style={{ width: "100%", height: 300 }}
          scale={level || 16}
          markers={markers}
          showScale={true}
          onTap={mapClick}
          enable-satellite={satellite}
          onRegionChange={regionChange}
        ></Map>
        {added && (
          <>
            <View className="controls item1" onClick={fn}>
              <Image
                src={require("../../../assets/images/left.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item2" onClick={fn2}>
              <Image
                src={require("../../../assets/images/right.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item3" onClick={fn3}>
              <Image
                src={require("../../../assets/images/top.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item4" onClick={fn4}>
              <Image
                src={require("../../../assets/images/bottom.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
          </>
        )}
      </View>

      <View className="button-wrap">
        <View className="button-item" onClick={changeSatellite}>
          {satellite ? "切换标准地图" : "切换卫星地图"}
        </View>
      </View>
      <AtForm>
        <AtInput
          required
          name="name"
          title="布点名称"
          type="text"
          placeholder="请输入布点名称"
          value={state.name}
          onChange={changename}
        />

        <AtInput
          name="tag"
          title="布点标签"
          type="text"
          placeholder="请输入布点标签"
          value={state.tag}
          onChange={changetag}
        />

        {/* <Picker
          mode="selector"
          range={selector}
          rangeKey="title"
          onChange={changestate}
        >
          <AtList>
            <AtListItem title="布点状态" extraText={state.pointstate.title} />
          </AtList>
        </Picker> */}

        <AtButton type="primary" onClick={onSubmit}>
          提交
        </AtButton>
      </AtForm>
      <AtMessage />
    </View>
  );
};

export default Index;
